package com.backend.server.controller;

import com.backend.server.service.UserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.common.server.common.BaseResponse;
import com.common.server.common.DeleteRequest;
import com.common.server.common.ErrorCode;
import com.common.server.common.ResultUtils;
import com.common.server.constant.UserConstant;
import com.common.server.entity.user.UserInfo;
import com.common.server.entity.user.dto.*;
import com.common.server.entity.user.vo.LoginUserInfoVO;
import com.common.server.entity.user.vo.UserInfoVO;
import com.common.server.exception.BusinessException;
import com.common.server.exception.ThrowUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * ClassName: UserInfoController
 * Package: com.user.server.controller
 * Description:
 *
 * @Author Memory
 * @Create 2024/12/26 14:14
 * @Version 1.0
 */

@RestController
@Api(value = "用户管理", tags = "用户管理")
@RequestMapping("/user")
@Slf4j
public class UserInfoController {

    @Resource
    private UserInfoService userInfoService;

    /**
     * 用户注册
     *
     * @param userInfoRegisterRequest 用户注册请求参数
     * @return 用户 id
     */
    @PostMapping("/register")
    @ApiOperation(value = "用户注册", notes = "用户注册")
    public BaseResponse<Long> userRegister(@RequestBody UserInfoRegisterRequest userInfoRegisterRequest) {
        // Controller 层对参数的校验
        if (userInfoRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userInfoRegisterRequest.getUserAccount();
        String userPassword = userInfoRegisterRequest.getUserPassword();
        String checkPassword = userInfoRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            return null;
        }
        long result = userInfoService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(result, "用户注册成功");
    }

    /**
     * 用户登录
     *
     * @param userInfoLoginRequest 用户登录请求参数
     * @param request              request
     * @return 登录用户信息
     */
    @PostMapping("/login")
    @ApiOperation(value = "用户登录", notes = "用户登录")
    public BaseResponse<Map<String, Object>> userLogin(@RequestBody UserInfoLoginRequest userInfoLoginRequest, HttpServletRequest request) {
        // Controller 层对参数的校验
        if (userInfoLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userInfoLoginRequest.getUserAccount();
        String userPassword = userInfoLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Map<String, Object> result = userInfoService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(result, "用户登录成功");
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation(value = "用户注销", notes = "用户注销")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userInfoService.userLogout(request);
        return ResultUtils.success(result, "用户注销成功");
    }

    /**
     * 创建用户
     *
     * @param userInfoAddRequest
     * @param request
     * @return
     */
    @ApiOperation(value = "创建用户", notes = "创建用户")
    @PostMapping("/add")
    public BaseResponse<Long> addUser(@RequestBody UserInfoAddRequest userInfoAddRequest, HttpServletRequest request) {
        if (userInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "创建用户信息不能为空");
        }
        String userAccount = userInfoAddRequest.getUserAccount();
        String userPassword = userInfoAddRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "创建用户信息不能为空");
        }
        // 查询用户是否存在
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        int count = userInfoService.count(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该用户(账号)已存在, 请重新输入");
        }
        // 2. 加密
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userInfoAddRequest, userInfo);
        String encryptPassword = DigestUtils.md5DigestAsHex((UserConstant.SALT + userPassword).getBytes());
        userInfo.setUserPassword(encryptPassword);

        boolean result = userInfoService.save(userInfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "保存信息出错, 创建用户失败");
        return ResultUtils.success(userInfo.getId(), "创建用户成功");
    }

    /**
     * 删除用户
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @ApiOperation(value = "删除用户", notes = "删除用户")
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "删除用户信息不能为空");
        }
        UserInfo one = userInfoService.getOne(new QueryWrapper<UserInfo>().eq("id", deleteRequest.getId()));
        ThrowUtils.throwIf(one == null, ErrorCode.NOT_FOUND_ERROR, "该用户不存在, 删除用户失败");
        boolean result = userInfoService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除用户失败");
        return ResultUtils.success(true, "删除用户成功");
    }

    /**
     * 更新用户
     *
     * @param userInfoUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @ApiOperation(value = "修改用户", notes = "修改用户")
    public BaseResponse<Boolean> updateUser(@RequestBody UserInfoUpdateRequest userInfoUpdateRequest, HttpServletRequest request) {
        if (userInfoUpdateRequest == null || userInfoUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "修改用户信息不能为空");
        }
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userInfoUpdateRequest, userInfo);
        boolean result = userInfoService.updateById(userInfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "用户信息更新失败");
        return ResultUtils.success(true, "用户信息更新成功");
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    @ApiOperation(value = "获取当前登录用户", notes = "获取当前登录用户")
    public BaseResponse<LoginUserInfoVO> getLoginUser(HttpServletRequest request) {
        UserInfo userInfo = userInfoService.getLoginUser(request);
        LoginUserInfoVO loginUserInfoVO = userInfoService.getLoginUserVO(userInfo);
        return ResultUtils.success(loginUserInfoVO, "获取当前登录用户成功");
    }

    /**
     * 获取用户列表(管理员)
     *
     * @param userInfoQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @ApiOperation(value = "获取用户列表(管理员)", notes = "获取用户列表(管理员)")
    public BaseResponse<Page<UserInfo>> listUserByPage(@RequestBody UserInfoQueryRequest userInfoQueryRequest, HttpServletRequest request) {
        long current = userInfoQueryRequest.getCurrent();
        long size = userInfoQueryRequest.getSize();
        Page<UserInfo> userPage = userInfoService.page(new Page<>(current, size), new QueryWrapper<>());
        userPage.setTotal(userPage.getRecords().size());
        return ResultUtils.success(userPage, "获取用户列表成功");
    }

    /**
     * 获取用户列表
     *
     * @param userInfoQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    @ApiOperation(value = "获取脱敏用户列表", notes = "获取脱敏用户列表")
    public BaseResponse<Page<UserInfoVO>> listUserVOByPage(@RequestBody UserInfoQueryRequest userInfoQueryRequest, HttpServletRequest request) {
        if (userInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = userInfoQueryRequest.getCurrent();
        long size = userInfoQueryRequest.getSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<UserInfo> userPage = userInfoService.page(new Page<>(current, size), new QueryWrapper<>());
        Page<UserInfoVO> userVOPage = new Page<>(current, size, userPage.getTotal());
        List<UserInfoVO> userInfoVOList = userInfoService.getUserInfoVO(userPage.getRecords());

        userVOPage.setRecords(userInfoVOList);
        userVOPage.setTotal(userInfoVOList.size());
        return ResultUtils.success(userVOPage, "获取脱敏用户列表成功");
    }
}
